import { mapState } from 'vuex'

export default {
  data() {
    return {
      chalk: "",
      defaultColor: '#409EFF'
    }
  },
  computed: {
    ...mapState({
      theme: 'theme'
    })
  },
  methods: {
    // 判断是否为颜色
    CheckIsColor(bgVal) {
      if (bgVal) {
        var type = "^#[0-9a-fA-F]{6}$"
        var re = new RegExp(type)
        if (bgVal.match(re) == null) {
          type =
            "^[rR][gG][Bb][(]([\\s]*(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)[\\s]*,){2}[\\s]*(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)[\\s]*[)]{1}$"
          re = new RegExp(type)
          if (bgVal.match(re) == null) {
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      }
    },
    // 更新主题系列色
    updateStyle(style, oldCluster, newCluster) {
      let newStyle = style
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, "ig"), newCluster[index])
      })
      return newStyle
    },
    // 初始化时获取默认主题的样式并复制给this.chalk
    getCSSString(callback, variable) {
      let styles = document.body.getElementsByTagName('style')
      let defaultCss = ''
      for (let i in styles) {
        if (styles[i].innerText && styles[i].innerText.includes(':root{--light-blue2:')) {
          if (!defaultCss) {
            defaultCss = styles[i].innerText.replace(/@font-face{[^}]+}/, "")
          }
        }
      }
      this[variable] = defaultCss
      callback()
    },
    // 获取到系列色
    getThemeCluster(theme) {
      const tintColor = (color, tint) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)

        if (tint === 0) {
          return [red, green, blue].join(",")
        } else {
          red += Math.round(tint * (255 - red))
          green += Math.round(tint * (255 - green))
          blue += Math.round(tint * (255 - blue))

          red = red.toString(16)
          green = green.toString(16)
          blue = blue.toString(16)

          return `#${red}${green}${blue}`
        }
      }

      const shadeColor = (color, shade) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)

        red = Math.round((1 - shade) * red)
        green = Math.round((1 - shade) * green)
        blue = Math.round((1 - shade) * blue)

        red = red.toString(16)
        green = green.toString(16)
        blue = blue.toString(16)

        return `#${red}${green}${blue}`
      }

      const clusters = [theme]
      for (let i = 0; i <= 9; i++) {
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
      }
      clusters.push(shadeColor(theme, 0.1))
      return clusters
    }
  },
  watch: {
    theme(val) {
      if (typeof val !== "string" || !val) return

      const themeCluster = this.getThemeCluster(val.replace("#", ""))
      const originalCluster = this.getThemeCluster(
        this.defaultColor.replace("#", "")
      )
      const getHandler = (variable, id) => {
        return () => {
          const newStyle = this.updateStyle(
            this[variable],
            originalCluster,
            themeCluster
          )
          let styleTag = document.getElementById(id)
          // 判断是否已经存在标签，么有则生成
          if (styleTag) {
            document.head.removeChild(styleTag)
          }
          styleTag = document.createElement("style")
          styleTag.setAttribute("id", id)
          document.head.appendChild(styleTag)

          // 替换为新的样式表
          styleTag.innerText = newStyle
        }
      }

      const chalkHandler = getHandler("chalk", "chalk-style-child")
      if (!this.chalk) {
        this.getCSSString(chalkHandler, "chalk", val)
        //更改模版初始颜色
        this.defaultColor = val
      } else {
        chalkHandler()
      }
    }
  }
}